package service

import (
	"errors"
	"fmt"
	"server/internal/model"
)

func (svc *Service) NewChainAccount(chainName, pwd, username string) (string, error) {
	form := make(map[string]interface{})
	form["pwd"] = pwd

	res, err := svc.Request(chainName, "/newAccount", form)
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	if res["data"] == nil {
		return "", errors.New("获取数据为nil")
	}

	ca := &model.ChainAccount{
		ChainName:    chainName,
		ChainAccount: res["data"].(string),
		Pwd:          pwd,
		Username:     username,
	}

	err = ca.Create(svc.engine)
	if err != nil {
		return "", err
	}

	return ca.ChainAccount, nil
}

func (svc *Service) GetChainAccounts(username string) ([]map[string]interface{}, error) {
	ca := &model.ChainAccount{
		Username: username,
	}
	accounts, err := ca.GetByUsername(svc.engine)
	if err != nil {
		return nil, err
	}

	len := len(accounts)
	accountArr := make([]map[string]interface{}, len)
	for i := 0; i < len; i++ {
		accountArr[i] = make(map[string]interface{})
		accountArr[i]["chainName"] = accounts[i].ChainName
		accountArr[i]["chainAccount"] = accounts[i].ChainAccount
		accountArr[i]["pwd"] = accounts[i].Pwd
		accountArr[i]["username"] = accounts[i].Username
		accountArr[i]["balance"] = accounts[i].Balance
	}

	return accountArr, err
}
